package com.talkyoung.ptbpro.common.util;

import com.talkyoung.ptbpojo.entity.User;
import com.talkyoung.ptbpojo.entity.UserExample;
import com.talkyoung.ptbpojo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.security.Principal;
import java.util.List;

/**
 * 用于从springsecurity中获取当前会话中的用户名称
 */
@Component
public class SecurityUserUtil {

    @Autowired
    private UserMapper userMapper;
    /**
     * 获取当前用户
     * @return
     */
    public static Authentication getCurrentUserAuthentication(){
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获取当前用户
     * @return
     */
    public static String getCurrentUserName(){
        Object principal = getCurrentUserAuthentication().getPrincipal();
        if (principal instanceof UserDetails) {
            return ((UserDetails) principal).getUsername();
        }

        if (principal instanceof Principal) {
            return ((Principal) principal).getName();
        }

        return String.valueOf(principal);
    }
}
